<?php
/**
 * phptm
 *
 * Copyright (c) 2009, Olivier Hoareau <hoareau.olivier@gmail.com>.
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 *   * Redistributions of source code must retain the above copyright
 *     notice, this list of conditions and the following disclaimer.
 *
 *   * Redistributions in binary form must reproduce the above copyright
 *     notice, this list of conditions and the following disclaimer in
 *     the documentation and/or other materials provided with the
 *     distribution.
 *
 *   * Neither the name of Olivier Hoareau nor the names of his
 *     contributors may be used to endorse or promote products derived
 *     from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
 * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
 * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
 * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
 * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
 * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 * POSSIBILITY OF SUCH DAMAGE.
 *
 * @package   phptm
 * @author    Olivier Hoareau <hoareau.olivier@gmail.com>
 * @copyright 2009 Olivier Hoareau <hoareau.olivier@gmail.com>
 * @license   http://www.opensource.org/licenses/bsd-license.php  BSD License
 * @since     File available since Release 0.1.0
 */
require_once 'PHPTM/TextUI/Getopt.php';
require_once 'PHPTM/Analyzer.php';
require_once 'PHPTM/TextUI/ResultPrinter.php';
require_once 'PHPTM/Log/XML/XML.php';
require_once 'PHPTM/Util/FilterIterator.php';
/**
 * TextUI frontend for PHPTM.
 *
 * @author    Johann-Peter Hartmann <johann-peter.hartmann@mayflower.de>
 * @author    Sebastian Bergmann <sb@sebastian-bergmann.de>
 * @author    Olivier Hoareau <hoareau.olivier@gmail.com>
 * @copyright 2009 Olivier Hoareau <hoareau.olivier@gmail.com>
 * @license   http://www.opensource.org/licenses/bsd-license.php  BSD License
 * @version   Release: @package_version@
 * @link      http://code.google.com/p/phptreematch  
 * @since     Class available since Release 0.1.0
 */
class PHPTM_TextUI_Command
{
    /**
     * Main method.
     */
    public static function main()
    {
        try {
            $options = PHPTM_TextUI_Getopt::getopt(
              $_SERVER['argv'],
              '',
              array(
                'help',
                'log-xml=',
                'suffixes=',
                'expected-tree=',
                'build-tree',
              'version'
              )
            );
        }

        catch (RuntimeException $e) {
            self::showError($e->getMessage());
        }

        $suffixes  = array();
        $expectedTree  = 'tree.xml';
        $mode = null;
        
        foreach ($options[0] as $option) {
            switch ($option[0]) {
                case '--log-xml': {
                    $logXml = $option[1];
                }
                break;

                case '--suffixes': {
                    $suffixes = explode(',', $option[1]);
                    array_map('trim', $suffixes);
                }
                case '--expected-tree': {
                    $expectedTree = $option[1];
                }
                break;

                case '--help': {
                    self::showHelp();
                    exit(0);
                }
                break;

                case '--version': {
                    self::printVersionString();
                    exit(0);
                }
                case '--build-tree': {
                    $mode = 'buildTree';
                }
                break;
            }
        }

        if ('buildTree' === $mode && isset($options[1][0])) {
            self::buildTree($options[1][0],$suffixes);
            exit(0);
            
        }
        if (isset($options[1][0])) {
            if (is_dir($options[1][0])) {
                $files = new PHPTM_Util_FilterIterator(
                  new RecursiveIteratorIterator(
                    new RecursiveDirectoryIterator($options[1][0])
                  ),
                  $suffixes
                );

                $commonPath = $options[1][0];
            }
        }

        if (!isset($files)) {
            self::showHelp();
            exit(1);
        }

        self::printVersionString();

        $results = PHPTM_Analyzer::analyze($commonPath,
          $files,PHPTM_Analyzer::parseTreeFile($expectedTree)
        );

        $printer = new PHPTM_TextUI_ResultPrinter;
        $printer->printResult($results, $commonPath . DIRECTORY_SEPARATOR);
        unset($printer);

        if (isset($logXml)) {
            $xml = new PHPTM_Log_XML_XML($logXml);
            $xml->processResults($results);
            unset($xml);
        }
    }

    /**
     * Shows an error.
     *
     * @param string $message
     */
    protected static function showError($message)
    {
        self::printVersionString();

        print $message;

        exit(1);
    }

    /**
     * Shows the help.
     */
    protected static function showHelp()
    {
        self::printVersionString();

        print <<<EOT
Usage: phptm [switches] <directory>

  --log-xml <file>            Write report in XML-TM XML format to file.

  --suffixes <suffix,...>     A comma-separated list of file suffixes to analyze.
  --expected-tree <tree.xml>  A tree xml file.
  
  --help                      Prints this usage information.
  --build-tree                Prints a tree xml file content for the specified directory.
  --version                   Prints the version and exits.

EOT;
    }

    /**
     * Builds the tree for the specified directory
     */
    protected static function buildTree($dir,$suffixes=array())
    {
        PHPTM_Analyzer::buildTreeFile($dir,fopen('php://stdout','w'),$suffixes);
    }
    
    /**
     * Prints the version string.
     */
    protected static function printVersionString()
    {
        print "phptm @package_version@ by Olivier Hoareau.\n\n";
    }
}
